package java_socket_long;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

public class Client {
    public static void main(String[] args) throws IOException, InterruptedException {
        Socket socket = new Socket("localhost", 12345);
        System.out.println("【客户端】开始准备");
        // 客户端也长连接
        socket.setKeepAlive(true);
        socket.setSendBufferSize(8192);
        socket.setReceiveBufferSize(8192);
        InputStream is = socket.getInputStream();
        OutputStream os = socket.getOutputStream();
        System.out.println("【客户端】请求开始");
        os.write("【客户端】请求发送测试1".getBytes("UTF-8"));
        os.flush();
        Thread.sleep(5 * 1000L);
        os.write("【客户端】请求发送测试2".getBytes("UTF-8"));
        os.flush();

        System.out.println("【客户端】读取服务器的返回");
        byte[] bytes = new byte[1024];
        while (is.read(bytes) > -1) {
            System.out.println(System.currentTimeMillis() + " received message: " + new String(bytes, "UTF-8").trim());
            bytes = new byte[1024];
        }
        Thread.sleep(5 * 1000L);
        os.write("【客户端】请求发送测试3".getBytes("UTF-8"));
        os.flush();

        System.out.println("【客户端】请求结束");
        if (!socket.isOutputShutdown()) {
            socket.shutdownOutput();
        }
        if (!socket.isInputShutdown()) {
            socket.shutdownInput();
        }
        if (!socket.isClosed()) {
            socket.close();
        }
        System.out.println("【客户端】关闭");
    }
}